package cn.team11.smarteye.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import cn.team11.sds.dayi.R;
import com.eques.icvss.api.ICVSSListener;
import com.eques.icvss.api.ICVSSUserInstance;
import com.eques.icvss.core.module.user.Buddy;
import com.eques.icvss.utils.Method;
import com.eques.icvss.utils.ResultCode;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.team11.smarteye.activity.CateyeDeviceDetailActivity;
import cn.team11.smarteye.activity.InComingActiviity;
import cn.team11.smarteye.bean.AlarmMsgInfoBean;
import cn.team11.smarteye.bean.CateyeEvent;
import cn.team11.smarteye.bean.CateyeInfoBean;
import cn.team11.smarteye.bean.RingRecordBean;
import cn.team11.smarteye.misc.SConstants;
import cn.team11.smarteye.module.ICVSSUserModule;
import cn.team11.smarteye.module.MyDaoManager;
import cn.team11.smarteye.utils.AppLogger;
import cn.team11.smarteye.utils.NetUtils;
import cn.team11.smarteye.utils.PreferencesUtils;
import cn.team11.smarteye.utils.TimeUtils;
import cn.team11.smarteye.utils.ToastUtil;

/**
 * Created by Murphy on 2017/10/30.
 */
public class CatEyeService extends Service implements ICVSSListener{


    private Object mlock;

    public static ICVSSUserInstance icvss;
    public static ICVSSUserModule icvssUserModule;
    private NetworkReceiver mNetworkReceiver;
    private CallReceiver mCallReceiver;
    private CallCloseReceiver mCloseReceiver;

    private boolean isCalling = false;//正在通话中或者等待来电等待中

    private boolean isNetworkAvailable = false;


    private String demoUrl = "thirdparty.ecamzone.cc:8443";
    private String username = "sdk_demo";
    //private String appkey = "sdk_demo";
    //private String keyid = "5d91e3b2b7fbb31c";
    private String appkey = "jhttPrj2KPeC2fSjaNBtkyh7QJJadxDm";
    private String keyid = "f5bff96034f0d5d8";


    @Override
    public void onCreate() {
        super.onCreate();
        mlock = new Object();
        //初始化preference
        PreferencesUtils.init(getApplicationContext(), SConstants.USER_PREFERENCE);
        //初始化猫眼sdk
        initMessageResponse();
        //注册网络状态监听器
        registerNetworkReceiver();
        //注册来电状态监听器
        registerCallReceiver();
        //
        registerIncomingCloseReceiver();
        /**
         * 测试用数据，根据实际情况替换
         * */
        //PreferencesUtils.putString(SConstants.USERNAME, username);
        PreferencesUtils.putString(SConstants.SERVER_URL, demoUrl);
        PreferencesUtils.putString(SConstants.APPKEY, appkey);
        PreferencesUtils.putString(SConstants.KEYID, keyid);


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (icvss == null) initMessageResponse();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new CateyeServiceBinder(this);
    }

    /**
     * 初始化猫眼SDK
     * */
    public void initMessageResponse(){
        synchronized (mlock) {
            icvssUserModule = ICVSSUserModule.getInstance(this);
            icvss = icvssUserModule.getIcvss();
        }
    }

    /**
     * 猫眼注销
     * */
    public void cateyeLogout(){
        if (icvss == null){
            AppLogger.e("CatEyeService.icvss is null.");
        } else if (icvss.equesIsLogin()){
            icvss.equesUserLogOut();//执行登出操作
        } else {
            AppLogger.d("user is not login.");
        }

    }


    /**
     * 猫眼登录
     * */
    public void cateyeLogin(){
        if (!NetUtils.isNetworkConnected(this)){
            EventBus.getDefault().post(new CateyeEvent.NetworkEvent(false));
            return;
        }
        if (icvss == null) {
            AppLogger.e("CatEyeService.icvss is null.");
        } else {
            if( !icvss.equesIsLogin()){
                String uname = PreferencesUtils.getString(SConstants.USERNAME);
                String surl = PreferencesUtils.getString(SConstants.SERVER_URL);
                String appkey = PreferencesUtils.getString(SConstants.APPKEY);
                icvss.equesLogin(this, surl, uname, appkey);
            }
        }
    }



    /**
     * service binder
     * */
    public class CateyeServiceBinder extends Binder{

        private CatEyeService service;

        public CateyeServiceBinder(CatEyeService service) {
            this.service = service;
        }

        public CatEyeService getService(){
            return service;
        }
    }

    /**
     * 登录状态检查
     * */
    public boolean isUserLogin(){
        String uname = PreferencesUtils.getString(SConstants.USERNAME);
        boolean isLogin = icvss.equesIsLogin();
        if (StringUtils.isEmpty(uname) || !isLogin){
            return false;
        }
        return true;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
    }

    @Override
    public void onDisconnect(int i) {
        ToastUtil.showPositiveToast("disconnect result = " + i);
    }

    @Override
    public void onPingPong(int i) {
        ToastUtil.showPositiveToast("onpingpong result = " + i);
    }

    @Override
    public void onMeaasgeResponse(JSONObject jsonObject) {

        if (jsonObject == null) return;
        AppLogger.i("json-result: " + jsonObject.toString());
        String method = jsonObject.optString(Method.METHOD);//获取方法名
        String devUid = jsonObject.optString(Method.ATTR_FROM);//获取设备的uid
        String bidTemp = null;

        if (StringUtils.isNotBlank(devUid)) {
            Buddy buddy = icvss.getBuddyByUid(devUid);//根据uid获取buddy
            if (buddy != null){
                bidTemp = buddy.getBid();
            } else {
                AppLogger.e("json-reuslt: onMeaasgeResponse getBuddyByUid is Null");
            }
        } else {
            AppLogger.e("json-result: onMeaasgeResponse devUid is Null");
        }

        if (Method.METHOD_EQUES_SDK_LOGIN.equals(method)) {//登录操作的响应
            int code = jsonObject.optInt(Method.ATTR_ERROR_CODE);
            if (code != ResultCode.SUCCESS) { //登录失败
                PreferencesUtils.putString(SConstants.USERNAME, "");//清除缓存的用户名
            } else {//登录成功
                icvss.equesGetDeviceList();//先获取设备列表
            }
            EventBus.getDefault().post(new CateyeEvent.ResultLogin(code));
        } else if (Method.METHOD_BDYLIST.equals(method)){
            JSONArray bdys = jsonObject.optJSONArray(Method.METHOD_BDYLIST);//设备列表
            JSONArray onlines = jsonObject.optJSONArray(Method.ATTR_ONLINES);//设备的在线列表，如果一个设备的在线列表为空，则表示该设备不在线

            //List<CateyeDeviceBean> devicesList = new ArrayList<>();
            // List<Map<String, CateyeDeviceBean>> devicesMaps = new ArrayList<>();
            //Map<String, CateyeDeviceBean> devicesMaps = new HashMap<>(); //设备MAP
            MyDaoManager.getInstance(this).deleteAllCateyeInfo();
            if (bdys != null && bdys.length()>0){//解析设备列表
                for (int i = 0; i < bdys.length(); i++){

                    JSONObject tmpObject = bdys.optJSONObject(i);
                    String name = tmpObject.optString(Method.ATTR_BUDDY_NAME);
                    String nick = tmpObject.optString(Method.ATTR_BUDDY_NICK);
                    String bid = tmpObject.optString(Method.ATTR_BUDDY_BID);
                    int role = tmpObject.optInt(Method.ATTR_ROLE);
                    CateyeInfoBean info = MyDaoManager.getInstance(this).getCateyeInfo(name);
                    if (info == null) {
                        info = new CateyeInfoBean();
                        info.setName(name);
                        MyDaoManager.getInstance(this).insertCateyeInfo(info);
                    }
                    info.setBid(bid);
                    info.setNick(nick);
                    info.setRole(role);
                    MyDaoManager.getInstance(this).updateCateyeInfo(info);
                }
            } else {
                MyDaoManager.getInstance(this).deleteAllCateyeInfo();
            }

            if (onlines != null && onlines.length()>0){//解析设备在线列表
                for (int i = 0; i< onlines.length(); i++){
                    JSONObject tmp = onlines.optJSONObject(i);

                    String bid = tmp.optString(Method.ATTR_BUDDY_BID, null);
                    String uid = tmp.optString(Method.ATTR_BUDDY_UID, null);
                    String nid = tmp.optString(Method.ATTR_BUDDY_NID, null);
                    int status = tmp.optInt(Method.ATTR_STATUS);
                    int localupg = tmp.optInt(Method.ATTR_BUDDY_LOCALUPG);
                    int remoteupg = tmp.optInt(Method.ATTR_BUDDY_REMOTEUPG);

                    //onlines列表里的设备一定包括再bdylist中
                    CateyeInfoBean info = MyDaoManager.getInstance(this).getCateyeInfoByBid(bid);

                    info.setUid(uid);
                    info.setNid(nid);
                    info.setStatus(status);
                    info.setLocalupg(localupg);
                    info.setRemoteupg(remoteupg);
                    MyDaoManager.getInstance(this).updateCateyeInfo(info);
                }
            }
            //获取所有的设备列表
            List<CateyeInfoBean> devices = MyDaoManager.getInstance(this).getAllCateyeInfo();
            EventBus.getDefault().post(new CateyeEvent.DevicesFoundEvent(devices));
        } else if (Method.METHOD_DEVICEINFO_RESULT.equals(method)){//设备详情
            if(!StringUtils.isEmpty(bidTemp)){
                CateyeInfoBean info = MyDaoManager.getInstance(this).getCateyeInfoByBid(bidTemp);
                info.setAlarm_enable(jsonObject.optInt(Method.METHOD_ALARM_ENABLE));
                info.setDb_light_enable(jsonObject.optInt(Method.METHOD_DB_LIGHT_ENABLE));
                info.setBattery_level(jsonObject.optInt("battery_level"));
                info.setBattery_status(jsonObject.optInt(Method.ATTR_BATTERY_STATUS));
                info.setDoorbell_ring(jsonObject.optInt("doorbell_ring"));
                info.setDoorbell_ring_name(jsonObject.optString("doorbell_ring_name"));
                info.setHw_version(jsonObject.optString("hw_version"));
                info.setSw_version(jsonObject.optString("sw_version"));
                info.setWifi_config(jsonObject.optString("wifi_config"));
                info.setStorage_free_size(jsonObject.optInt("storage_free_size"));
                info.setStorage_total_size(jsonObject.optInt("storage_total_size"));
                info.setWifi_level(jsonObject.optInt("wifi_level"));
                MyDaoManager.getInstance(this).updateCateyeInfo(info);
                EventBus.getDefault().post(info);
            }
        } else if (Method.METHOD_ALARM_ALMLIST.equals(method)){//报警消息列表
            JSONArray alarms = jsonObject.optJSONArray(Method.ATTR_ALARMS);
            MyDaoManager.getInstance(this).deleteAllAlarms();
            if (alarms != null || alarms.length() > 0){
                for (int i = 0; i < alarms.length(); i++ ){
                    JSONObject temp = alarms.optJSONObject(i);
                    String tempAid = temp.optString(Method.ATTR_ALARM_AID);
                    AlarmMsgInfoBean bean = MyDaoManager.getInstance(this).getAlarmMsg(tempAid);
                    if (bean == null){//本地报警消息不存在
                        bean = new AlarmMsgInfoBean();
                        bean.setAid(temp.optString(Method.ATTR_ALARM_AID));
                        bean.setBid(temp.optString(Method.ATTR_BUDDY_UID));
                        bean.setAlarmDexSn(temp.optString(Method.ATTR_ALARM_DEV_SN));
                        bean.setCreate(temp.optLong(Method.ATTR_ALARM_CREATE));
                        JSONArray fidsArray = temp.optJSONArray(Method.ATTR_FID);
                        List<String> fids = new ArrayList<>();
                        for (int j = 0; j< fidsArray.length(); j++){
                            fids.add(fidsArray.optString(j));
                        }
                        bean.setFid(fids);
                        bean.setTime(temp.optLong(Method.ATTR_ALARM_TIME));
                        JSONArray pvidsArray = temp.optJSONArray(Method.ATTR_ALARM_PVID);
                        List<String> pvids = new ArrayList<>();
                        for (int k = 0; k<pvidsArray.length(); k++){
                            pvids.add(pvidsArray.optString(k));
                        }
                        String[] dtString = TimeUtils.times(bean.getTime()).split("#");
                        String savedPath = SConstants.ROOT_PATH
                                + File.separator + SConstants.ALARM_MSG
                                + File.separator + dtString[0].replace("-","")
                                + File.separator + dtString[1].replace(":", "");//暂时只下载第一个
                        bean.setPath(savedPath);
                        bean.setPvid(pvids);
                        bean.setType(temp.optInt(Method.ATTR_ALARM_TYPE));
                        MyDaoManager.getInstance(this).insertAlarmMsg(bean);
                    }
                }
            }

        } else if (Method.METHOD_ALARM_RINGLIST.equals(method)){//门铃记录列表
            JSONArray ringlists = jsonObject.optJSONArray(Method.ATTR_RINGS);
            MyDaoManager.getInstance(this).deleteAllRings();
            if (ringlists != null || ringlists.length() > 0){
                for (int i = 0; i < ringlists.length(); i++){
                    JSONObject temp = ringlists.optJSONObject(i);
                    String bid = temp.optString(Method.ATTR_BUDDY_BID);
                    Long time = temp.optLong(Method.ATTR_RING_TIME);
                    RingRecordBean ring = new RingRecordBean();
                    ring.setBid(temp.optString(Method.ATTR_BUDDY_BID));
                    ring.setRingtime(temp.optLong(Method.ATTR_RING_TIME));
                    ring.setFid(temp.optString(Method.ATTR_FID));
                    MyDaoManager.getInstance(this).insertRingMsg(ring);
                }
            }
        } else if (Method.METHOD_ONADDBDY_REQ.equals(method)){//设备端（ wifi 猫眼）扫描客户端生成的二维码
            String name = jsonObject.optString(Method.ATTR_BDYNAME);
            String reqid = jsonObject.optString(Method.ATTR_REQID);
            String oldbyd = jsonObject.optString(Method.ATTR_OLDBDY);

            CateyeEvent.RequestBinding requestBinding = new CateyeEvent.RequestBinding(name, null, reqid, oldbyd);
            EventBus.getDefault().post(requestBinding);
        } else if (Method.METHOD_ONADDBDY_RESULT.equals(method)){//客户端回复是否同意添加设备
            int code = jsonObject.optInt(Method.ATTR_ERROR_CODE);
            EventBus.getDefault().post(new CateyeEvent.ResultBinding(code));

        } else if (Method.METHOD_CALL.equals(method)){
            String uid = jsonObject.optString(Method.ATTR_FROM);
            String state = jsonObject.optString(Method.ATTR_CALL_STATE);
            //String to = jsonObject.optString(Method.ATTR_TO);

            AppLogger.i("isCalling = " + isCalling);
            if ("close".equals(state)){
                //EventBus.getDefault().post(new CateyeEvent.VideoCallCloseEvent(ResultCode.SUCCESS));
                isCalling = false;
            } else if ("open".equals(state)){//发生门铃事件后回调
                CateyeInfoBean itemInfo = MyDaoManager.getInstance(this).getCateyeInfoByBid(bidTemp);
                if (isCalling){
                    EventBus.getDefault().post(new CateyeEvent.CloseCurrentCallEvent(isCalling));
                    isCalling = false;
                } else {
                    AppLogger.i("ready to incoming view.");
                    Intent intent = new Intent(this, InComingActiviity.class);
                    intent.putExtra(SConstants.UID, uid);
                    intent.putExtra(SConstants.BID, bidTemp);
                    intent.putExtra(SConstants.NAME, itemInfo.getName());
                    intent.putExtra(SConstants.NICKNAME, itemInfo.getNick());
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    isCalling = true;
                }
            }

        } else if (Method.METHOD_PREVIEW.equals(method)) { //门铃发生时，抓拍一张图片过来
            String inComingCallImgFid = jsonObject.optString(Method.ATTR_ALARM_FID);
            EventBus.getDefault().post(new CateyeEvent.IncomingCallPreviewEvent(inComingCallImgFid));
            RingRecordBean newring = new RingRecordBean();
            newring.setBid(bidTemp);
            newring.setFid(jsonObject.optString(Method.ATTR_FID));
            newring.setRingtime(jsonObject.optLong("filetime"));
            MyDaoManager.getInstance(this).insertRingMsg(newring);

            RingRecordBean recordBean = MyDaoManager.getInstance(this).getRingMsgByBidAndTime(bidTemp, newring.getRingtime());
            EventBus.getDefault().post(new CateyeEvent.NewRingRecordEvent(recordBean));


        } else if (Method.METHOD_LOCKLIST.equals(method)) {//获取门锁列表

        } else if (Method.METHOD_BINDLOCK.equals(method)){ //锁在其它客户端绑定消息

        } else if (Method.METHOD_UNBINDLOCK.equals(method)) { //锁在其它客户端解绑消息

        } else if (Method.METHOD_LOCK_MSG_LIST.equals(method)){//门锁消息

        } else if (Method.METHOD_LOCK_ALARM_LIST.equals(method)){//门锁报警信息

        } else if (Method.METHOD_VIDEOPLAY_STATUS_PLAYING.equals(method)){//视频画面开始播放
            isCalling = true;
            EventBus.getDefault().post(new CateyeEvent.VideoStatusEvent(SConstants.VIDEO_PLAY));

        } else if (Method.METHOD_ALARM_NEWALM.equals(method)){//设备发生报警消息通知
            showNotification(bidTemp);//发出通知
            //更新本地报警数据库
            AlarmMsgInfoBean newalm = new AlarmMsgInfoBean();
            newalm.setAid(jsonObject.optString(Method.ATTR_ALARM_AID));
            newalm.setBid(jsonObject.optString(Method.ATTR_BUDDY_BID));
            newalm.setCreate(jsonObject.optLong(Method.ATTR_ALARM_CREATE));
            JSONArray fidsArray = jsonObject.optJSONArray(Method.ATTR_FID);
            List<String> fids = new ArrayList<>();
            for (int j = 0; j< fidsArray.length(); j++){
                fids.add(fidsArray.optString(j));
            }
            newalm.setFid(fids);
            newalm.setTime(jsonObject.optLong(Method.ATTR_ALARM_TIME));
            JSONArray pvidsArray = jsonObject.optJSONArray(Method.ATTR_ALARM_PVID);
            List<String> pvids = new ArrayList<>();
            for (int k = 0; k<pvidsArray.length(); k++){
                pvids.add(pvidsArray.optString(k));
            }
            String[] dtString = TimeUtils.times(newalm.getTime()).split("#");
            String savedPath = SConstants.ROOT_PATH
                    + File.separator + SConstants.ALARM_MSG
                    + File.separator + dtString[0].replace("-","")
                    + File.separator + dtString[1].replace(":", "");//暂时只下载第一个
            newalm.setPath(savedPath);
            newalm.setPvid(pvids);
            newalm.setType(jsonObject.optInt(Method.ATTR_ALARM_TYPE));
            MyDaoManager.getInstance(this).insertAlarmMsg(newalm);
            //发送NewAlarm事件
            AlarmMsgInfoBean savedNewAlm = MyDaoManager.getInstance(this).getAlarmMsg(newalm.getAid());
            EventBus.getDefault().post(new CateyeEvent.NewAlarmEvent(savedNewAlm));

        } else if (Method.METHOD_DELETE_ALARM.equals(method)){//删除报警响应

        } else if (Method.METHOD_DELETE_RING.equals(method)){//删除门铃记录

        } else if (Method.METHOD_RMBDY_RESULT.equals(method)){//删除设备
            int code = jsonObject.optInt(Method.ATTR_ERROR_CODE);
            EventBus.getDefault().post(new CateyeEvent.DeleteDeviceEvent(code));

        } else if (Method.METHOD_ONBDY_REMOVED.equals(method)){//其它登录该账户（支持多客户端同时登录）的客户端会收到服务器下发设备被删除的消息

        } else if (Method.METHOD_ALARM_ENABLE_RESULT.equals(method)){//人体侦测开关
            int code = jsonObject.optInt(Method.ATTR_SETTINGS_RESULT);
            if (code == 1){
                EventBus.getDefault().post(new CateyeEvent.EnablePirEvent(ResultCode.SUCCESS));
            }else {
                EventBus.getDefault().post(new CateyeEvent.EnablePirEvent(ResultCode.ERROR));
            }
        } else if (Method.METHOD_DB_LIGHT_ENABLE_RESULT.equals(method)){//门铃灯开关

        } else if (Method.METHOD_SETNICK.equals(method)){//设备重命名
            int ret = jsonObject.optInt(Method.ATTR_ERROR_CODE);
            EventBus.getDefault().post(new CateyeEvent.SetNickEvent(ret));
        } else if (Method.METHOD_RESTART_DEVICE_RESULT.equals(method)){
            int ret = jsonObject.optInt(Method.ATTR_SETTINGS_RESULT);
            if (ret == 1){
                EventBus.getDefault().post(new CateyeEvent.RestartEvent(ResultCode.SUCCESS));
            }else {
                EventBus.getDefault().post(new CateyeEvent.RestartEvent(ResultCode.ERROR));
            }

        }

    }

    private void registerNetworkReceiver(){
        if (mNetworkReceiver == null){
            mNetworkReceiver = new NetworkReceiver(this);
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            registerReceiver(mNetworkReceiver, filter);
        }
    }

    private void registerCallReceiver(){
        if (mCallReceiver == null){
            mCallReceiver = new CallReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.intent.action.PHONE_STATE");
            registerReceiver(mCallReceiver, filter);
        }
    }

    private void registerIncomingCloseReceiver(){
        if (mCloseReceiver == null){
            mCloseReceiver = new CallCloseReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(SConstants.INCOMING_CLOSE_ACTION);
            registerReceiver(mCloseReceiver, filter);
        }
    }


    private void unregisterReceiver(){
        if (mNetworkReceiver != null){
            unregisterReceiver(mNetworkReceiver);
            mNetworkReceiver = null;
        }
        if (mCallReceiver != null){
            unregisterReceiver(mCallReceiver);
            mCallReceiver = null;
        }
        if (mCloseReceiver != null){
            unregisterReceiver(mCloseReceiver);
            mCloseReceiver = null;
        }
    }


    /**显示通知*/
    private void showNotification(String bid){
        Intent intent = new Intent();
        intent.setClass(this, CateyeDeviceDetailActivity.class);
        intent.putExtra(SConstants.BID, bid);
        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

        NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                //设置通知标题
                .setContentTitle(getString(R.string.alert_message))
                //设置通知内容
                .setContentText(getString(R.string.body_detection_alerm))
                .setAutoCancel(true)
                .setWhen(System.currentTimeMillis())
                .setContentIntent(pi);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            //设置横幅通知
            builder.setFullScreenIntent(pi, false);
        }

        mNotifyManager.notify(1, builder.build());


    }


    class NetworkReceiver extends BroadcastReceiver {

        private CatEyeService mService;

        public NetworkReceiver(CatEyeService mService) {
            this.mService = mService;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            //检查网络情况
            if (!NetUtils.isNetworkConnected(context)){//网络不可用
                EventBus.getDefault().post(new CateyeEvent.NetworkEvent(false));
            } else {
                EventBus.getDefault().post(new CateyeEvent.NetworkEvent(true));
            }
        }
    }

    class CallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //监听来电
            TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
            tm.listen(new PhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);
            AppLogger.i("incoming call state is" + tm.getCallState());
            if (tm.getCallState() == TelephonyManager.CALL_STATE_RINGING){
                EventBus.getDefault().post(new CateyeEvent.PhoneCallEvent(1));
            }
        }

    }

    class CallCloseReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //
            isCalling = false;
        }
    }

    class PhoneListener extends PhoneStateListener {

        public PhoneListener() {}

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            AppLogger.i("call " + incomingNumber + " state is "+ state);
            if (state == TelephonyManager.CALL_STATE_RINGING){
                EventBus.getDefault().post(new CateyeEvent.PhoneCallEvent(state));
            }
        }


    }

}
